package cn.tedu.supermarket.controller;

import cn.tedu.supermarket.mapper.UserMapper;
import cn.tedu.supermarket.pojo.dto.UserLoginDTO;
import cn.tedu.supermarket.pojo.dto.UserRegDTO;
import cn.tedu.supermarket.pojo.entity.User;
import cn.tedu.supermarket.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Objects;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;
    @RequestMapping("/reg")
    public int reg(@RequestBody UserRegDTO user){
        UserVO userVO=mapper.selectByPropertyId(user.getPropertyId());
        if (userVO!=null){
            return 2;
        }
        System.out.println("user = " + user);
        User u = new User();
        BeanUtils.copyProperties(user,u);
        u.setTime(new Date());
        u.setIntegral(0);
        mapper.insert(u);
        return 1;
    }
    @RequestMapping("/login")
    public int login(@RequestBody UserLoginDTO user, HttpSession session){
        UserVO userVO=mapper.selectByPropertyId(user.getPropertyId());
        if (userVO!=null){
            if (Objects.equals(userVO.getPassword(),user.getPassword())){
                session.setAttribute("user",userVO);
                return 1;
            }
            return 2;
        }
        return 3;
    }
    @RequestMapping("/currentUser")
    public UserVO currentUser(HttpSession session){
        return (UserVO)session.getAttribute("user");
    }

}
